package com.taurus.isms;

import java.util.Map;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;



import android.content.BroadcastReceiver;

import android.content.Context;
import android.support.v4.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.Loader;
import android.database.Cursor;
import android.support.v4.app.Fragment;
import android.text.Editable;

import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.GestureDetector;

import android.view.LayoutInflater;

import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;

import android.widget.FilterQueryProvider;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.OverScroller;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.LoaderManager.LoaderCallbacks;

import com.taurus.isms.ThreadsAdapter;
import com.taurus.isms.threads.ContactsData;
import com.taurus.isms.threads.ThreadsSearchResultAdapter;
import com.taurus.wiget.IOSSearchView;
import com.taurus.wiget.IOSSearchView.OnStatusChangedListener;
import com.taurus.wiget.ListViewEx;


public class ThreadsFragment extends Fragment implements
		LoaderCallbacks<Cursor> {

	private static final String TAG = "ThreadsFragment";
	private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
	// ������==========
	InputMethodManager imMgr;
	private IOSSearchView searchView;
	private SimpleCursorAdapter mSearchAdapter;
	private ListView srchRsltLst;
	private View listFrameView;
    private ImageView newSmsButton;

	private ListViewEx listThreads;
	private SimpleCursorAdapter adapter;
	private ThreadsAdapter threadsAdapter;
	private Cursor mCursor;

	private int animDuration = 300;

	private SMSBroadcastReceiver smsBroadcastReceiver;
	private IntentFilter filter;
	public static final Uri MMSSMS_FULL_CONVERSATION_URI = Uri
			.parse("content://mms-sms/conversations");
	public static final Uri CONVERSATION_URI = MMSSMS_FULL_CONVERSATION_URI
			.buildUpon().appendQueryParameter("simple", "true").build();

	private Map<String, String> personNameMap;
	private GestureDetector mGesture = null;

	private int mTouchSlop;
	private ItemControl itemControl;
	private ContactsData mContactsData;
	
	

	/**
	 * ��Activity�����Ľӿ�
	 * 
	 */

	public OnThreadsItemClickListener mOnThreadsItemClickListener;
	public interface OnThreadsItemClickListener{
		public void onClick(View v,long threadId,long smsId,CharSequence contactName);
	}
	
	public void setOnThreadsItemClickListener(OnThreadsItemClickListener onThreadsItemClickListener){
		mOnThreadsItemClickListener = onThreadsItemClickListener;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//return super.onCreateView(inflater, container, savedInstanceState);
		return inflater.inflate(R.layout.activity_threads, container,false);
	}	
	
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
   
		mTouchSlop = ViewConfiguration.get(getActivity())
				.getScaledTouchSlop();

		imMgr = (InputMethodManager) getActivity().getSystemService(
				Context.INPUT_METHOD_SERVICE);
		
		
		// ������start--------------------------------------------------------------

		searchView = new IOSSearchView(getActivity());	
		srchRsltLst = (ListView) getActivity().findViewById(R.id.srchRsltLst);
		srchRsltLst.setVisibility(View.GONE);
		initSearchBar();
		
		listThreads = (ListViewEx) getActivity().findViewById(R.id.listThreads);
		listThreads.addHeaderView(searchView);
		
        listThreads.setOnItemClickListener(listThreadsItemClickListener);
		
		listFrameView = (View) getActivity().findViewById(R.id.listlayout);
		

		
		itemControl = new ItemControl(listThreads,threadsAdapter);
		itemControl.setOnItemControlItemClickListner(new OnItemControlItemClickListner(){

			@Override
			public void onClick(View v, int position, long id) {
				if(mOnThreadsItemClickListener!=null){
				
					String contactName="";
					
					mOnThreadsItemClickListener.onClick(v, id, 0, contactName);
				}
			}
			
			
		});				
		
		
		listThreads.setOnTouchListener(itemControl);


		// ������end-----------------------------------------------------------------


		getLoaderManager().initLoader(0, null, this);
		threadsAdapter = new ThreadsAdapter(getActivity());
		mContactsData = new ContactsData(getActivity());
		threadsAdapter.setContactsData(mContactsData);
		listThreads.setAdapter(threadsAdapter);
		//
		smsBroadcastReceiver = new SMSBroadcastReceiver();
		filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
		
		Log.d("TAG:::::::", "endddddddddddd");
	}


    private void initSearchBar(){
    	
    	
    	
    	
    	String[] FROM = {"ADDRESS","DATE","BODY"};
    	int[] TO = {R.id.receiveAt,R.id.textUser,R.id.textText};
    	mSearchAdapter = new ThreadsSearchResultAdapter(getActivity());
    	
    	FilterQueryProvider filterQueryProvider = new FilterQueryProvider(){

			@Override
			public Cursor runQuery(CharSequence constraint) {
				
			    Uri uri = Uri.parse("content://sms/inbox");
				Log.d(TAG, "SearchFilterQueryProvider Constraint is : " + constraint);

				String[] projection = new String[] { "_ID","THREAD_ID","ADDRESS","PERSON","DATE","PROTOCOL","READ","STATUS","TYPE","BODY","SERVICE_CENTER" };

				String selection = " BODY LIKE '%" + constraint
						+ "%' ";

				 Cursor cursor = getActivity().getContentResolver().query(
						uri,
						projection, selection, null, null);
				 Log.d("ContactFilterQueryProvider", "cursor is : " + cursor.getCount());
				 return cursor;
			}
    		
    	};
    	
    	mSearchAdapter.setFilterQueryProvider(filterQueryProvider);
    	
    	TextWatcher watcher = new TextWatcher(){

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if(s.length()<=0){
					mSearchAdapter.swapCursor(null);
					srchRsltLst.setBackgroundColor(0x77000000);
					return;
				}
				srchRsltLst.setBackgroundColor(0xFFFFFFFF);
				Cursor cursor = mSearchAdapter.runQueryOnBackgroundThread(s);			
				mSearchAdapter.swapCursor(cursor);
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
    		
    	};
    	
    	searchView.setOnTextChangedListener(watcher);
//    	searchView.setAdapter(mSearchAdapter);
    	srchRsltLst.setAdapter(mSearchAdapter);
    	
    	OnStatusChangedListener onStatusChangedListener = new IOSSearchView.OnStatusChangedListener() {
			
			@Override
			public void onChanged(View layout,int status) {
				// TODO Auto-generated method stub
				if(status== IOSSearchView.STATUS_EDIT){
				
				listThreads.setSelectionFromTop(0, 0);;
				
				int height = layout.getHeight();
				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)srchRsltLst.getLayoutParams();
				params.topMargin = height;
				srchRsltLst.setLayoutParams(params);
				srchRsltLst.setBackgroundColor(0x77000000);
				srchRsltLst.setVisibility(View.VISIBLE);
				
				
				}else{
					srchRsltLst.setVisibility(View.GONE);
				}
			}
		};
		
		searchView.setOnStatusChangedListener(onStatusChangedListener);
		
		
		ItemControl itemControl = new ItemControl(srchRsltLst,mSearchAdapter);
		itemControl.setOnItemControlItemClickListner(new OnItemControlItemClickListner(){

			@Override
			public void onClick(View v, int position, long id) {
				
				if(mOnThreadsItemClickListener!=null){
					Cursor cursor = mSearchAdapter.getCursor();
					if(cursor.moveToPosition(position)){
					long threadId = cursor.getLong(cursor.getColumnIndex("thread_id"));
					long smsId =  cursor.getLong(cursor.getColumnIndex("_id"));
					CharSequence contactName ="";
					mOnThreadsItemClickListener.onClick(v, threadId, smsId, contactName);
					}
				}
			}
			
		});
		
		srchRsltLst.setOnTouchListener(itemControl);
		
		
		
		
    	
    }

	
	
	/**
	 * �б��item����¼�
	 * 
	 */
	AdapterView.OnItemClickListener  listThreadsItemClickListener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Log.d("ThreadsAcitivty","listThreads OnItemClick+++");

			
			//TODO:
//			TextView tv =(TextView) view.findViewById(R.id.textUser);
			
//			String threadId = tv.getTag().toString().trim();
//			
//			String contactName =tv.getText().toString().trim();
//			Intent intent = new Intent(getActivity(),ChatActivity.class);			
//			intent.putExtra("contact_name", contactName);
//			intent.putExtra("thread_id", threadId);
//			ThreadsActivity.this.startActivity(intent);
			
		}
		
	};
	
	

	/**********************************
	 * �����Ƕ���Ч��
	 * 
	 */

	/****************************************
	 * �������¼������� **************************************
	 */

	


	View.OnClickListener editBtnClick = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
	    //TODO:itemControl
			itemControl.changeEditState(true);
		}
	};

	
	public void changeListEditState(boolean flag){
		itemControl.changeEditState(true);
	}
	

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.threads, menu);
//		return true;
//	}

	
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	public void onResume() {

		super.onResume();


		getActivity().registerReceiver(smsBroadcastReceiver, filter);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	public void onPause() {

		super.onPause();

		getActivity().unregisterReceiver(smsBroadcastReceiver);
	}

	// ����ת��ʱ��
	static final ViewBinder VIEW_BINDER = new ViewBinder() {

		@Override
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

			if (view.getId() == R.id.receiveAt) {

				long timestamp = cursor.getLong(columnIndex);
				CharSequence relTime = DateUtils.getRelativeTimeSpanString(
						view.getContext(), timestamp);
				((TextView) view).setText(relTime);
				return true;
			}

			return false;

		}

	};

	class SMSBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {

			// cursor.requery();
			Toast.makeText(getActivity(), "have a new message!!",
					Toast.LENGTH_LONG).show();
			threadsAdapter.notifyDataSetChanged();

			Log.d("ThreadsReciever", "onRecieved");
		}

	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {

		String[] projection = { "_ID", "DATE", "MESSAGE_COUNT",
				"RECIPIENT_IDS", "SNIPPET", "SNIPPET_CS", "READ", "TYPE",
				"ERROR", "HAS_ATTACHMENT" };
		return new CursorLoader(this.listThreads.getContext(),
				CONVERSATION_URI, projection, null, null, "DATE DESC");
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
        mCursor=arg1;
		threadsAdapter.swapCursor(arg1);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {

		threadsAdapter.swapCursor(null);
	}

	
	
    public interface OnItemControlItemClickListner{
    	public void onClick(View v,int position ,long id);
    }
	class ItemControl implements OnTouchListener {
        private ListView iListView;
        private ListAdapter iListAdapter;
        private OnItemControlItemClickListner iOnItemControlItemClickListner;
		private View itemView;
		private View slideItemView;
		private Button rowBtnView;
		private Button batchDelBtn;

		private int rowBtnViewWidth;
		private int batchDelBtnWidth;

		private int downX;
		private int downY;
		private int moveX;
		private int moveY;
		private int upX;
		private int upY;
		private int preMoveX;
		private int preMoveY;
		private int preTouchItemPosition = Integer.MAX_VALUE;

		private int itemState;
		private int NORMAL = 0;
		private int SCROLL_TO_SHOW_DELETE = 1;
		private int SCROLL_TO_HIDE_DELETE = 2;
		private int ITEM_EDIT = 3;
		private int ITEM_EDIT_END = 4;
		private int SPRING_END = 5;
		private int SPRINGING = 6;
		private int TO_SHOW_EDIT = 7;
		private int TO_HIDE_EDIT = 8;
		private int TO_SHOW_EDIT_END = 9;
		private int TO_HIDE_EDIT_END = 10;

		private boolean isAnotherItem = false;
		private boolean isInvalidPosition = false;
		private OverScroller scroller;
        private boolean isSingleItemEdit = false;
        
   
        public void setOnItemControlItemClickListner(OnItemControlItemClickListner onItemControlItemClickListner){
        	iOnItemControlItemClickListner =onItemControlItemClickListner;
        }
        
        
        ItemControl(ListView listView,ListAdapter listAdapter){
        	iListView = listView;
        	iListAdapter = listAdapter;
        }
        
		private Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				Log.d("ItemControl", "handleMessage");
				int arg1 = msg.arg1;
				int dx = msg.what;

				if (arg1 == SPRINGING||arg1 == SPRING_END) {
					if (slideItemView != null) {
						Log.d("ItemControl",
								"handleMessage:slideItemView:scrollBy:" + dx);
						slideItemView.scrollTo(dx, 0);
						slideItemView.postInvalidate();

					}

					if (msg.arg1 == SPRING_END
							&& itemState == SCROLL_TO_HIDE_DELETE) {
						if(iListView instanceof ListViewEx){
							ListViewEx list = (ListViewEx)iListView;
							list.setScrollable(true);
						}
						
						preTouchItemPosition = Integer.MAX_VALUE;
						isAnotherItem = false;
						itemState = NORMAL;
						isSingleItemEdit = false;
						Log.d("ItemControl","handler:itemState = NORMAL");
					}
				} else if (arg1 == TO_SHOW_EDIT || arg1 == TO_SHOW_EDIT_END
						|| arg1 == TO_HIDE_EDIT || arg1 == TO_HIDE_EDIT_END) {

					int childCnt = iListView.getChildCount();
					int left = msg.what;
					float alpha = msg.arg2 * 0.001f;
					Log.d("ItemControl","handle:left:" + left +" alpha:" + alpha+"childCnt:"+childCnt);
					//Toast.makeText(getApplicationContext(), "Left:"+left, Toast.LENGTH_SHORT);
					for (int i = 0; i <= childCnt ; i++) {
						try {
							View item = iListView.getChildAt(i);
							View slideItem = item
									.findViewById(R.id.rowSlideView);
							Button btnView = (Button)item.findViewById(R.id.batchDelBtn);
							
							int top = slideItem.getPaddingTop();
							int right = slideItem.getPaddingRight();
							int bottom = slideItem.getPaddingBottom();
							slideItem.setPadding(left, top, right, bottom);
							btnView.setAlpha(alpha);
							
							if(arg1 == TO_SHOW_EDIT_END){
								btnView.setEnabled(true);
								
							}else if(arg1 == TO_HIDE_EDIT_END){
								btnView.setEnabled(false);
							}

						} catch (Exception e) {
							Log.d("ItemControl","handler:Exception:i:"+i);
							e.printStackTrace();
						}

					}
                      
					
					if (arg1 == TO_HIDE_EDIT_END) {
						itemState = NORMAL;
					}

				}

				super.handleMessage(msg);
			}

		};

		public boolean springTo(int fromX, int toX) {
			Log.d("ItemControl", "springTo");
			final int distanceX = toX - fromX;
			final int fx = fromX;
			final int tx = toX;
			new Thread() {

				@Override
				public void run() {
					Log.d("ItemControl", "Thread:run");
					float dx = distanceX;
					float scrollByX;
					float scrollX;
					while (!Thread.interrupted() && Math.abs(dx) > 2.0f) {
						Log.d("ItemControl", "Thread:run:dx=" + dx);

						scrollByX = (float) (dx * 0.35);
						dx = dx - scrollByX;
						scrollX = tx - dx;
						Message msg = new Message();
						msg.arg1 = SPRINGING;
						msg.what = (int) scrollX;
						handler.sendMessage(msg);

						try {
							Thread.sleep(50);
						} catch (Exception e) {
							e.printStackTrace();

						}
					}

					Message msg = new Message();

					msg.what = (int) tx;
					msg.arg1 = SPRING_END;
					handler.sendMessage(msg);

					super.run();
				}

			}.start();

			return true;
		}

		@Override
		public boolean onTouch(View v, MotionEvent ev) {
             Log.d("ItemControl","OnTouch......");
             
			switch (ev.getAction()) {
			case MotionEvent.ACTION_DOWN:
				Log.d("ItemControl","OnTouch:ACTION_DOWN");
				downX = (int) ev.getX();
				downY = (int) ev.getY();
				preMoveX = downX;
				preMoveY = downY;

				int pos = iListView.pointToPosition((int) downX, (int) downY);
				int headerViewCount = iListView.getHeaderViewsCount();
				Log.d("ItemControl","OnTouch:ACTION_DOWN:pos = "+pos +"  headerViewCount = "+headerViewCount);
				if(pos <=headerViewCount){
					isInvalidPosition =true;
					break;
				}else{
					isInvalidPosition = false;
				}
				
				if (isAnotherItem == false && itemState != NORMAL && itemState == SCROLL_TO_SHOW_DELETE
						&& preTouchItemPosition != Integer.MAX_VALUE
						&& preTouchItemPosition != pos) {
					switchButton();
					itemState = SCROLL_TO_HIDE_DELETE;
					//TODO:
					rowBtnView.setEnabled(false);
					springTo(slideItemView.getScrollX(), 0);
					isAnotherItem = true;
					return false;
				} else if (isAnotherItem == true) {
					return false;
				}
				
				
				

				
				preTouchItemPosition = pos;
				itemView = iListView.getChildAt(pos
						- iListView.getFirstVisiblePosition());
                

				
				slideItemView = itemView.findViewById(R.id.rowSlideView);
				rowBtnView = (Button)itemView.findViewById(R.id.rowBtnView);
				batchDelBtn = (Button)itemView.findViewById(R.id.batchDelBtn);
				rowBtnViewWidth = rowBtnView.getWidth();
                
                
				break;
			case MotionEvent.ACTION_MOVE:
				Log.d("ItemControl","OnTouch:ACTION_MOVE");
				
				if(isInvalidPosition){
					return false;
				}
				moveX = (int) ev.getX();
				moveY = (int) ev.getY();
				int distanceX = preMoveX - moveX;
				int distanceY = preMoveY - moveY;
				preMoveX = moveX;
				preMoveY = moveY;

				int scrollX = slideItemView.getScrollX() + distanceX;
				if (isAnotherItem == true) {
					Log.d("ItemControl","OnTouch:ACTION_MOVE��return false");
					return false;
				}
				// ����Item
				if (itemState == NORMAL && scrollX>0
						&& Math.abs(distanceX) > mTouchSlop
						&& Math.abs(distanceY) < mTouchSlop ) {
					switchButton();
					itemState = SCROLL_TO_SHOW_DELETE;
					
					if(iListView instanceof ListViewEx){
						ListViewEx list = (ListViewEx)iListView;
						list.setScrollable(false);
					}
					Log.d("ItemControl","OnTouch:ACTION_MOVE��isScrollable");
				}

				if (itemState == SCROLL_TO_SHOW_DELETE && scrollX >= 0) {
					// ���������ť��ȣ���������
					if (scrollX > rowBtnViewWidth) {
						
						distanceX = (int) (distanceX * 0.25f);
					}
					
					Log.d("ItemControl","OnTouch:ACTION_MOVE��ScrollBy");
					slideItemView.scrollBy(distanceX, 0);
					if(scrollX > 0){
						isSingleItemEdit = true;
					}else{
					    isSingleItemEdit = false;		
					}
					
						
				}
				break;
			case MotionEvent.ACTION_UP:
				Log.d("ItemControl","OnTouch:ACTION_UP");
				
				if(isInvalidPosition){
					return false;
				}
				
				if (isAnotherItem == true) {
					return false;
				}
//				Toast.makeText(getApplicationContext(), "onSingleTapUp",
//						Toast.LENGTH_SHORT).show();
				Log.d("ItemControl", "onSingleTapUp");

				upX = (int) ev.getX();
				upY = (int) ev.getY();
				int dx = upX - downX;
				int dy = upY - downY;
                 
				// ������󻬶�δ������ɾ������ť��60%�����ᴥ�������ԭ��λ�ã��������60%�����������ť��100%�������Ѱ�ť��ʾ����
				if ((slideItemView.getScrollX() < (rowBtnViewWidth * 0.6 )
						|| Math.abs(dx) < mTouchSlop)&&slideItemView.getScrollX()>0) {
					Log.d("ItemControl", "onSingleTapUp:ScrollX:"
							+ slideItemView.getScrollX());
					switchButton();
					itemState = SCROLL_TO_HIDE_DELETE;
					rowBtnView.setEnabled(false);
					springTo(slideItemView.getScrollX(), 0);
					
				} else if(slideItemView.getScrollX()>0){
					itemState = SCROLL_TO_SHOW_DELETE;
					rowBtnView.setEnabled(true);
					springTo(slideItemView.getScrollX(), rowBtnViewWidth);
				}else if(Math.abs(dx) < mTouchSlop && Math.abs(dy) < mTouchSlop){
					//TODO;����¼�
					Log.d("ThreadsAcitivty","listView OnItemClick");	
					int position = iListView.pointToPosition(upX, upY);	
					long id = iListView.getItemIdAtPosition(position);
					if(iOnItemControlItemClickListner!= null){
						iOnItemControlItemClickListner.onClick(v, position,id);
					}
					

				}
				

				break;

			}

			return false;
		}

		public void setListEdit(boolean isEdit) {

			final int paddingLeft = 100;

			if (isEdit) {
				itemState = ITEM_EDIT;
				if( iListAdapter instanceof  ThreadsAdapter)
				{
					ThreadsAdapter adapter = (ThreadsAdapter)iListAdapter;
					adapter.setSlideViewPaddingLeft(paddingLeft);
				}
				new Thread() {

					@Override
					public void run() {
						int tPaddingLeft = 0;
						int endPadding = paddingLeft;
						int alpha = 0;
						while (!Thread.interrupted() && endPadding > 2) {
							int tmpVar;
							tmpVar = (int) (endPadding * 0.35f);
							endPadding = endPadding - tmpVar;
							tPaddingLeft += tmpVar;
							
							alpha = tPaddingLeft * 550/paddingLeft;
							
							Message msg = new Message();
							msg.arg1 = TO_SHOW_EDIT;
							msg.arg2 = alpha;
							msg.what = tPaddingLeft;
							handler.sendMessage(msg);

							try {
								Thread.sleep(20);
							} catch (Exception e) {

								e.printStackTrace();
							}

						}

						Message msg = new Message();
						msg.arg1 = TO_SHOW_EDIT_END;
						msg.arg2 = 1000;
						msg.what = paddingLeft;
						handler.sendMessage(msg);

						super.run();
					}

				}.start();

			} else {
				itemState = ITEM_EDIT;
				if( iListAdapter instanceof  ThreadsAdapter)
				{
					ThreadsAdapter adapter = (ThreadsAdapter)iListAdapter;
					adapter.setSlideViewPaddingLeft(0);
				}
				new Thread() {

					@Override
					public void run() {
						int tPaddingLeft = 0;
						int endPadding = paddingLeft;
						int alpha = 0;
						while (!Thread.interrupted() && endPadding > 2) {
							int tmpVar;
							tmpVar = (int) (endPadding * 0.35f);
							endPadding = endPadding - tmpVar;
							tPaddingLeft = endPadding;
							
							alpha = tPaddingLeft * 550 /paddingLeft;
							
							Message msg = new Message();
							msg.arg1 = TO_HIDE_EDIT;
							msg.arg2 = alpha;
							msg.what = tPaddingLeft;
							handler.sendMessage(msg);

							try {
								Thread.sleep(20);
							} catch (Exception e) {

								e.printStackTrace();
							}

						}

						Message msg = new Message();
						msg.arg1 = TO_HIDE_EDIT_END;
						msg.arg2 = 1000;
						msg.what = 0;
						handler.sendMessage(msg);

						super.run();
					}

				}.start();

			}

		}
		
		public boolean changeEditState(boolean isButtonClick){
			//����ǵ���item������ʾ��ť����1.��editBtn��ť���ı���Ϊ����ɡ���tag��Ϊ��1����
			if(itemState == SCROLL_TO_SHOW_DELETE)
			{
				Log.d("ItemControl","changeEditState:SCROLL_TO_SHOW_DELETE:isButtonClick:"+isButtonClick);
				//TODO:�ѹ����˵ĵ���item����ԭλ
				itemState = SCROLL_TO_HIDE_DELETE;
				springTo(slideItemView.getScrollX(), 0);
				//TODO:��editBtn��ť���ı���Ϊ"�༭"��tag��Ϊ0��
				switchButton();	
			}else if(itemState == NORMAL){
				
				Log.d("ItemControl","changeEditState:NORMAL:isButtonClick:"+isButtonClick);
				if(isButtonClick){
					//TODO:��ʾ����ɾ����ťbatchDeleteButton
					
					setListEdit(true);
				}
				//TODO:�ı�editBtn��ť���ı���Ϊ����ɡ���tag��Ϊ1
				switchButton();	
			}else if(itemState == ITEM_EDIT){
				Log.d("ItemControl","changeEditState:ITEM_EDIT:isButtonClick:"+isButtonClick);
			//TODO:��������ɾ����ťbatchDeleteButton
				
				setListEdit(false);
		    //TODO:��editBtn��ť���ı���Ϊ"�༭"��tag��Ϊ0��
				switchButton();			
			}
			
			return true;			
		}
		
		
		public void switchButton(){
			
			//�ı��任���䶯��
			AlphaAnimation m = new AlphaAnimation(1.0f, 0.0f);
			m.setDuration(150);
			
			m.setAnimationListener(new Animation.AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {

				}

				@Override
				public void onAnimationRepeat(Animation animation) {

				}

				@Override
				public void onAnimationEnd(Animation animation) {
                   // Log.d("ItemControl","switchButton:tag:"+editBtn.getTag().toString());
//					if (editBtn.getTag().toString().compareTo("0")==0) {
//						 Log.d("ItemControl","switchButton:text:"+"���");
//						editBtn.setTag("1");
//						editBtn.setText("���");	
//						
//                         //TODO:�����༭��bug��������Itemʱ�ı䡰�༭��ť����״̬��
//					} else {
//						Log.d("ItemControl","switchButton:text:"+"�༭");
//						editBtn.setTag("0");
//						editBtn.setText("�༭");
//						newSmsButton.setVisibility(View.VISIBLE);
//						searchViewInput.setEnabled(true);
//						
//					}
				}
			});
//			editBtn.startAnimation(m);
//			if (editBtn.getTag().toString().compareTo("0")==0) {
//				newSmsButton.setVisibility(View.GONE);
//				searchViewInput.setEnabled(false);
//				
//			} 
			
			
			
			
		}

	}

}
